package implementation.data.records;

import java.util.ArrayList;

import java.util.List;

import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


import implementation.server.IReadOnlyForum;

public class CForumRecord implements IReadOnlyForum, Cloneable {

	
	private int _forumId;
	private String _forumName;
	private List<Integer> _myThreads;
	private final ReentrantReadWriteLock _rwl;
	private final Lock _r;
	private final Lock _w;
	
	public CForumRecord(int forumId, String forumName){
		this._forumId = forumId;
		this._forumName = forumName;
		this._myThreads = Collections.synchronizedList(new ArrayList<Integer>());
		this._rwl = new ReentrantReadWriteLock();
		this._r = this._rwl.readLock();
		this._w = this._rwl.writeLock();
	}
	
	public String getName(){
		return this._forumName;
	}
	
	public int getID(){
		return this._forumId;
	}
	
		
	public boolean addThread(int threadId){
		
		this._w.lock();
		try{
			return this._myThreads.add(threadId);
		}
		finally {this._w.unlock();}
	}
	
	public ArrayList<Integer> getThreads(){
		
		
		this._r.lock();
		try
		{
			ArrayList<Integer> tAnswer= new ArrayList<Integer>();
		
	
			int tTo = this._myThreads.size();
			for(int index=0; index < tTo; index++)
				tAnswer.add(this._myThreads.get(index));
		

			return tAnswer;
		}
		finally {this._r.unlock();}
	}
	
	
	public String toString(){
		String tAnswer="My Id is: "+ this._forumId+ "\nForum Name: "+ this._forumName+"\n"+ "Threads Id: "+ getThreads()+ "\n";
		
		return tAnswer;
	}
		

	public CForumRecord clone(){
		
		
		this._r.lock();
		try
		{
			CForumRecord tCForumRecord = new CForumRecord(this._forumId, this._forumName);
			int tTo = this._myThreads.size();
			for(int index=0; index < tTo; index++)
				tCForumRecord.addThread(this._myThreads.get(index));
			
			return tCForumRecord;
		}
		finally {this._r.unlock();}
		

	}
}
